package com.leo.ibatis.demo.dao.ibatis;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.util.Assert;

import com.leo.ibatis.demo.criteria.ProfileCriteria;
import com.leo.ibatis.demo.dao.ProfileDao;
import com.leo.ibatis.demo.domain.Profile;
import com.leo.ibatis.demo.util.Paging;

public class ProfileDaoImpl extends SqlMapClientDaoSupport implements ProfileDao {

	public void insert(Profile profile) throws DataAccessException {
		getSqlMapClientTemplate().insert("Profile.insert", profile);
	}

	public int update(Profile profile) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().update("Profile.update", profile, actualRowsAffected);

		return actualRowsAffected;
	}

	public int delete(String userid) throws DataAccessException {
		int actualRowsAffected = 1;

		getSqlMapClientTemplate().delete("Profile.delete", userid, actualRowsAffected);

		return actualRowsAffected;
	}

	public Profile select(String userid) throws DataAccessException {
		return (Profile) getSqlMapClientTemplate().queryForObject("Profile.select", userid);
	}

	@SuppressWarnings("unchecked")
	public List<Profile> list(ProfileCriteria profileCriteria) throws DataAccessException {
		Assert.notNull(profileCriteria, "profileCriteria must not be null");
		
		return getSqlMapClientTemplate().queryForList("Profile.list", profileCriteria);
	}

	@SuppressWarnings("unchecked")
	public List<Profile> listOnPage(ProfileCriteria profileCriteria) throws DataAccessException {
		Assert.notNull(profileCriteria, "profileCriteria must not be null");
		Assert.notNull(profileCriteria.getPaging(), "paging must not be null");
		
		int totalResults = count(profileCriteria);
		Paging paging = profileCriteria.getPaging();
		paging.setTotalResults(totalResults);
		
		return getSqlMapClientTemplate().queryForList("Profile.list", profileCriteria, paging.getFirstResult(), paging.getMaxResults());
	}

	public int count(ProfileCriteria profileCriteria) throws DataAccessException {
		Assert.notNull(profileCriteria, "profileCriteria must not be null");
		
		return ((Integer) getSqlMapClientTemplate().queryForObject("Profile.count", profileCriteria)).intValue();
	}

}
